package com.jfirer.mvc.resolver.impl;

import com.jfirer.baseutil.StringUtil;
import com.jfirer.mvc.annotation.HeaderValue;
import com.jfirer.mvc.resolver.AbstractParamResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HeaderResolver extends AbstractParamResolver
{

    private final String headerName;
    private final String defaultValue;
    private       Class  ckass;

    public HeaderResolver(Class<?> ckass, String paramName, HeaderValue headerValue)
    {
        super(paramName);
        this.ckass = ckass;
        String headerName   = headerValue.value();
        String defaultValue = headerValue.defaultValue();
        if (headerName.equals(""))
        {
            headerName = paramName;
        }
        if (defaultValue.equals(""))
        {
            defaultValue = null;
        }
        this.headerName = headerName;
        this.defaultValue = defaultValue;
    }

    @Override
    public Object resolve(HttpServletRequest request, HttpServletResponse response)
    {
        String value = request.getHeader(headerName);
        value = StringUtil.isNotBlank(value) ? value : StringUtil.isNotBlank(defaultValue) ? defaultValue : null;
        if (value == null)
        {
            return null;
        }
        else
        {
            return toValue(ckass, value);
        }
    }
}
